package com.eqdd.yiqidian.web;

import android.content.DialogInterface;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;

import com.eqdd.yiqidian.JustWebActivityCustom;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.base.AppConstent;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.http.HttpConfig;
import com.google.gson.Gson;
import com.just.agentweb.AgentWeb;
import com.just.agentweb.ChromeClientCallbackManager;
import com.just.agentweb.DefaultWebClient;

import java.util.regex.Pattern;

/**
 * @author吕志豪 .
 * @date 17-11-16  下午1:18.
 * Github :https://github.com/lvzhihao100
 * E-Mail：1030753080@qq.com
 * 简书 :http://www.jianshu.com/u/6e525b929aac
 */

public class JustWebActivity extends BaseActivity {

    private JustWebActivityCustom dataBinding;
    private AlertDialog mAlertDialog;
    private boolean isLogin;
    private AgentWeb mAgentWeb;
    private String url;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isKeyBoardJustPan = false;
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_just_web);
        initTopTitleBar(View.VISIBLE, "关于易企点");
    }

    @Override
    public void initData() {
        String title = getIntent().getStringExtra(Config.TITLE);
        url = getIntent().getStringExtra(Config.URL);
        isLogin = getIntent().getBooleanExtra(Config.IS_LOGIN, false);
        //System.out.println(url);
        if (!TextUtils.isEmpty(url)) {
            boolean matches = Pattern.matches("^http[s]?://[\\S]*?$", url.toLowerCase());
            if (!matches) {
//                initTopTitleBar(View.VISIBLE, TextUtils.isEmpty(title) ? "信息" : title);
//                dataBinding.wvContent.setVisibility(View.GONE);
//                dataBinding.tvContent.setVisibility(View.VISIBLE);
//                dataBinding.tvContent.setText(url);
            } else {
//                Intent in = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
//                startActivity(in);
//                finish();
                dataBinding.includeTitle.tvTitle.setText(title);
                initWeb();
            }
        } else {
            dataBinding.includeTitle.tvTitle.setText(title);
            url = Config.URL_ABOUT_US;
            initWeb();
        }
    }

    private void initWeb() {
        mAgentWeb = AgentWeb.with(this)//
                .setAgentWebParent(dataBinding.llRoot, new LinearLayout.LayoutParams(-1, -1))//
                .useDefaultIndicator()//
                .defaultProgressBarColor()
//                .setIndicatorColorWithHeight(-1, 3)
                .setReceivedTitleCallback(mCallback)
                .setWebChromeClient(mWebChromeClient)
                .setWebViewClient(mWebViewClient)
                .setMainFrameErrorView(R.layout.agentweb_error_page, -1)
                .setSecurityType(AgentWeb.SecurityType.strict)
//                .setWebLayout(new WebLayout(this))
                .openParallelDownload()//打开并行下载 , 默认串行下载
                .setNotifyIcon(R.drawable.ic_file_download_black_24dp) //下载图标
                .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.ASK)//打开其他应用时，弹窗咨询用户是否前往其他应用
                .interceptUnkownScheme() //拦截找不到相关页面的Scheme
                .createAgentWeb()//
                .ready()
                .go(getUrl());
    }

    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return super.shouldOverrideUrlLoading(view, request);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            //do you  work
            if (isLogin) {
                mAgentWeb.getJsEntraceAccess().quickCallJs("onLogin", new Gson().toJson(AppConstent.user));
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (isLogin) {
                mAgentWeb.getJsEntraceAccess().quickCallJs("onLogin", new Gson().toJson(AppConstent.user));
            }
        }
    };
    private WebChromeClient mWebChromeClient = new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            //do you work
//            Log.i("Info","progress:"+newProgress);
        }
    };

    public String getUrl() {

        return url;
    }

    private ChromeClientCallbackManager.ReceivedTitleCallback mCallback = new ChromeClientCallbackManager.ReceivedTitleCallback() {
        @Override
        public void onReceivedTitle(WebView view, String title) {
            dataBinding.includeTitle.tvTitle.setText(title);
        }
    };


    private void showDialog() {

        if (mAlertDialog == null)
            mAlertDialog = new AlertDialog.Builder(this)
                    .setMessage("您确定要关闭该页面吗?")
                    .setNegativeButton("再逛逛", (dialog, which) -> {
                        if (mAlertDialog != null)
                            mAlertDialog.dismiss();
                    })//
                    .setPositiveButton("确定", (dialog, which) -> {

                        if (mAlertDialog != null)
                            mAlertDialog.dismiss();

                        JustWebActivity.this.finish();
                    }).create();
        mAlertDialog.show();

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (mAgentWeb.handleKeyEvent(keyCode, event)) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onPause() {
        mAgentWeb.getWebLifeCycle().onPause();
        super.onPause();

    }

    @Override
    protected void onResume() {
        mAgentWeb.getWebLifeCycle().onResume();
        super.onResume();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        Log.i("Info", "result:" + requestCode + " result:" + resultCode);
        mAgentWeb.uploadFileResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //mAgentWeb.destroy();
        mAgentWeb.getWebLifeCycle().onDestroy();
    }

    @Override
    public void setView() {
//        Intent intent = new Intent();
//        intent.setAction("android.intent.action.VIEW");
//        Uri content_url = Uri.parse(HttpConfig.ABOUT_US);
//        intent.setData(content_url);
//        startActivity(intent);
    }


    @Override
    protected void onStop() {
        super.onStop();
//        this.finish();
    }
}
